﻿//----------------------------------------------------------------------------------------------------
// The FileInterface is used for saving and laoding of files.
//----------------------------------------------------------------------------------------------------

package HG.TypeInterfaces
{
	import flash.net.FileReference;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.events.*;
	import flash.net.URLRequest;
	import flash.utils.ByteArray;
	
	import HG.Debug;
	
	public class IFileInterface
	{
		var m_URLLoader:URLLoader = new URLLoader();
		var m_fileReference:FileReference = new FileReference();
		var m_file:String;
		var m_loaded:Boolean;
		var m_data:ByteArray;
		var m_callback:Function;
		
		//----------------------------------------------------------------------------------------------------
		public function IFileInterface()
		{
			m_loaded = false;
		}
		
		//----------------------------------------------------------------------------------------------------
		public function SetFile(file:String)
		{
			m_file = file;
		}
		
		//----------------------------------------------------------------------------------------------------
		public function Load(callback:Function)
		{
			Debug.ASSERT(m_file, "Attempted to load null file");
			
			m_callback = callback;
			
			m_URLLoader.addEventListener(Event.COMPLETE, OnLoadComplete);
			m_URLLoader.dataFormat = URLLoaderDataFormat.BINARY;
			m_URLLoader.load(new URLRequest(m_file));
		}
		
		//----------------------------------------------------------------------------------------------------
		protected function Save(bytes:ByteArray)
		{
			m_fileReference.save(bytes, m_file);
		}
		
		//----------------------------------------------------------------------------------------------------
		protected function OnLoadComplete(evt:Event):void 
		{
			m_data.position = 0;
			m_data = m_URLLoader.data;
			m_loaded = true;
			//callback(m_URLLoader.data);
		}
		
		//----------------------------------------------------------------------------------------------------
		public function Loaded():Boolean
		{
			return m_loaded;
		}
		
		//----------------------------------------------------------------------------------------------------
		public function GetData():ByteArray
		{
			return m_data;
		}
		
		
		
		//----------------------------------------------------------------------------------------------------
	}
	
}
